import { createRouter, createWebHistory } from 'vue-router'
import useToken from '../store/token'
import Index from '../pages/Index.vue'
import notification from '../utils/notification'

const router = createRouter({
    history: createWebHistory(),
    routes: [{
        path: '/',
        redirect: '/index',
        component: Index,
        meta: { title: '首页' },
        children: [{
            path: 'Index',
            name: 'index',
            component: () =>
                import ('../pages/subpages/Index.vue'),
            meta: { title: '首页' }
        }, {
            path: 'Category',
            component: () =>
                import ('../pages/subpages/Category.vue'),
            meta: { title: '分类管理' },
        }, {
            path: 'Goods',
            component: () =>
                import ('../pages/subpages/Goods.vue'),
            meta: { title: '商品管理' },
        }, {
            path: 'Setting',
            component: () =>
                import ('../pages/subpages/Setting.vue'),
            meta: { title: '个人中心' },
        }]
    }, {
        path: '/login',
        name: 'login',
        component: () =>
            import ('../pages/login.vue'),
        meta: { title: '登录' },
    }, ]
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
    document.title = to.meta.title + ' - ' + '后台管理系统'
    const { token } = useToken()
    if (token) {
        next()
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            notification({
                message: '请先登录',
                type: 'error'
            })
            next('/login')
        }
    }
})
export default router